﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Runtime.InteropServices;

namespace RadioPlayer
{
	public partial class RadioPlayerMainForm : Form
	{
		/*	TODO LIST :
		*		- OnClose de la manage form on refresh la liste de radios
		*		
		*	A VERIFIER
		*		- Minimize in tray : correction problème notifyIcon visible et form visible en même temps !!! (lock session)
		*/

		private TextBox m_tbUrl;
        private RadioHelper m_listeRadios;

		public RadioPlayerMainForm()
		{
			InitializeComponent();
			
            m_listeRadios = new RadioHelper();
            List<RadioObject> liste = m_listeRadios.Liste;
            foreach (RadioObject radio in liste)
            {
                cbRadioList.Items.Add(radio);
            }
			m_tbUrl = (TextBox)FindControlInMP3StreamingPanel("textBoxStreamingUrl");

			Button btnPlay = (Button)FindControlInMP3StreamingPanel("buttonPlay");
			Button btnPause = (Button)FindControlInMP3StreamingPanel("buttonPause");
			Button btnStop = (Button)FindControlInMP3StreamingPanel("buttonStop");
			btnPause.Enabled = false;
			btnStop.Enabled = false;

			streamPlayer.OnPlayClick += delegate {
				cbRadioList.Enabled = false;
				btnPlay.Enabled = false;
				btnPause.Enabled = true;
				btnStop.Enabled = true;
				m_tbUrl.Enabled = false;
			};

			streamPlayer.OnStopClick += delegate {
				cbRadioList.Enabled = true;
				btnPlay.Enabled = true;
				btnPause.Enabled = false;
				btnStop.Enabled = false;
				m_tbUrl.Enabled = true;
			};
		}

		private Control FindControlInMP3StreamingPanel(string szName)
		{
			Control ctlRet = new Control();
			Control[] tbList = streamPlayer.Controls.Find(szName, true);
			foreach (Control tb in tbList)
			{
				if (tb.Name == szName)
					ctlRet = tb;
			}
			return ctlRet;
		}

		private void exitToolStripMenuItem_Click(object sender, EventArgs e)
		{
			Application.Exit();
		}

		private void manageRadiosToolStripMenuItem_Click(object sender, EventArgs e)
		{
			RadioManagement form = new RadioManagement();
			form.Show();
		}

		private void alwaysOnTopToolStripMenuItem_Click(object sender, EventArgs e)
		{
			alwaysOnTopToolStripMenuItem.Checked = !alwaysOnTopToolStripMenuItem.Checked;
			RadioPlayer.RadioPlayerMainForm.ActiveForm.TopMost = alwaysOnTopToolStripMenuItem.Checked;
		}

        private void cbRadioList_SelectedIndexChanged(object sender, EventArgs e)
        {
            RadioObject selectedRadio = (RadioObject)cbRadioList.SelectedItem;
            m_tbUrl.Text = selectedRadio.StreamUrl;
        }

		private void RadioPlayerMainForm_Resize(object sender, EventArgs e)
		{
			if (WindowState == FormWindowState.Minimized && minimizeOnTrayToolStripMenuItem.Checked)
			{
				Form form1 = Form.ActiveForm;
				notifyIcon1.Visible = true;
				notifyIcon1.Icon = RadioPlayer.Properties.Resources.casque_radio_soutien_voicecall_icone_6111;

				notifyIcon1.DoubleClick += delegate {
					if (form1.WindowState == FormWindowState.Minimized)
					{
						form1.Show();
						form1.WindowState = FormWindowState.Normal;
						if (notifyIcon1.Visible)
							notifyIcon1.Visible = false;
					}
					else
						notifyIcon1.Visible = false;
				};
				try {
					form1.Hide();
					notifyIcon1.Visible = true;
				}
				catch (Exception) {};
			}
		}

		private void stopOnWindowsSessionLockToolStripMenuItem_Click(object sender, EventArgs e)
		{
			stopOnWindowsSessionLockToolStripMenuItem.Checked = !stopOnWindowsSessionLockToolStripMenuItem.Checked;
		}

		private void minimizeOnTrayToolStripMenuItem_Click(object sender, EventArgs e)
		{
			minimizeOnTrayToolStripMenuItem.Checked = !minimizeOnTrayToolStripMenuItem.Checked;
		}

#region windows session
		//Source : http://blogs.msdn.com/b/shawnfa/archive/2005/05/17/418891.aspx

		// from wtsapi32.h
		private const int NotifyForThisSession = 0;

		// from winuser.h
		private const int SessionChangeMessage = 0x02B1;
		private const int SessionLockParam = 0x7;
		private const int SessionUnlockParam = 0x8;

		[DllImport("wtsapi32.dll")]
		private static extern bool WTSRegisterSessionNotification(IntPtr hWnd, int dwFlags);

		[DllImport("wtsapi32.dll")]
		private static extern bool WTSUnRegisterSessionNotification(IntPtr hWnd);

		// flag to indicate if we've registered for notifications or not
		private bool registered = false;

		/// <summary>
		/// Is this form receiving lock / unlock notifications
		/// </summary>
		protected bool ReceivingLockNotifications
		{
			get { return registered; }
		}

		/// <summary>
		/// Unregister for event notifications
		/// </summary>
		protected void aLaFin(bool disposing)
		{
			if (registered)
			{
				WTSUnRegisterSessionNotification(Handle);
				registered = false;
			}
			base.Dispose(disposing);
			return;
		}

		/// <summary>
		/// Register for event notifications
		/// </summary>
		protected override void OnHandleCreated(EventArgs e)
		{
			base.OnHandleCreated(e);

			// WtsRegisterSessionNotification requires Windows XP or higher
			bool haveXp = Environment.OSVersion.Platform == PlatformID.Win32NT &&
							(Environment.OSVersion.Version.Major > 5 ||
							(Environment.OSVersion.Version.Major == 5 &&
							Environment.OSVersion.Version.Minor >= 1));

			if (haveXp)
				registered = WTSRegisterSessionNotification(Handle, NotifyForThisSession);
			return;
		}

		/// <summary>
		/// The windows session has been locked
		/// </summary>
		protected virtual void OnSessionLock()
		{
			if (stopOnWindowsSessionLockToolStripMenuItem.Checked)
				streamPlayer.StopClick();

			return;
		}

		/// <summary>
		/// The windows session has been unlocked
		/// </summary>
		protected virtual void OnSessionUnlock()
		{
			if (stopOnWindowsSessionLockToolStripMenuItem.Checked)
				streamPlayer.PlayClick();

			return;
		}

		/// <summary>
		/// Process windows messages
		/// </summary>
		protected override void WndProc(ref Message m)
		{
			// check for session change notifications
			if (m.Msg == SessionChangeMessage)
			{
				if (m.WParam.ToInt32() == SessionLockParam)
					OnSessionLock();
				else if (m.WParam.ToInt32() == SessionUnlockParam)
					OnSessionUnlock();
			}
			base.WndProc(ref m);
			return;
		}

		private void RadioPlayerMainForm_FormClosing(object sender, FormClosingEventArgs e)
		{
			aLaFin(true);
		}
#endregion
	}
}